package com.kyxx.topics.fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.kyxx.topics.BaseApp;
import com.kyxx.topics.R;
import com.kyxx.topics.activity.MessageActivity;
import com.kyxx.topics.activity.SearchActivity;
import com.kyxx.topics.activity.SignActivity;
import com.kyxx.topics.adapter.MainTabFragmentAdapter;
import com.kyxx.topics.adapter.TabFragmentAdapter;
import com.kyxx.topics.bean.TagBean;
import com.kyxx.topics.net.OkGoRequest;
import com.kyxx.topics.net.ResponseListener;
import com.kyxx.topics.net.RestClient;
import com.kyxx.topics.net.UrlUtils;
import com.kyxx.topics.utils.ToastUtils;
import com.kyxx.topics.widget.HeaderViewPagerFragment;
import com.loopj.android.http.RequestParams;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.HttpParams;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import cz.msebera.android.httpclient.Header;
import okhttp3.Call;
import okhttp3.Response;

public class MainFragment extends Fragment {
    private LinearLayout top_bar;
    private LinearLayout ll_search;
    private RelativeLayout rl_message;
    private TextView tv_message_num;
    private ImageView iv_sign;
    private TabLayout tl;
    private ViewPager vp;
    private PopupWindow popupWindow;
    private LinearLayout ll_tab;
    private View layout;
    private LinearLayout ll_arrow_down;
    private LinearLayout ll_arrow_up;
    private String[] titles = new String[]{"精选", "送女票", "海淘", "创意生活", "送基友", "送爸妈", "送同事", "送宝贝", "设计感", "文艺风", "奇葩搞怪", "科技范", "萌萌哒"};
    private List<TagBean> tagBeanList = new ArrayList<>();

    @Override
    public void onResume() {
        super.onResume();
        getMessageCount();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            getMessageCount();
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_main, container, false);
        top_bar = (LinearLayout) view.findViewById(R.id.top_bar_main);
        ll_search = (LinearLayout) view.findViewById(R.id.ll_search);
        rl_message = (RelativeLayout) view.findViewById(R.id.rl_message);
        tv_message_num = (TextView) view.findViewById(R.id.tv_message_num);
        iv_sign = (ImageView) view.findViewById(R.id.iv_sign);
        tl = (TabLayout) view.findViewById(R.id.tl);
        vp = (ViewPager) view.findViewById(R.id.vp);
        ll_tab = (LinearLayout) view.findViewById(R.id.ll_tab);
        ll_arrow_down = (LinearLayout) view.findViewById(R.id.ll_arrow_down);
        ll_arrow_down.setOnClickListener(onClickListener);
        ll_search.setOnClickListener(onClickListener);
        rl_message.setOnClickListener(onClickListener);
        initPopupWindow();
        initTag();
        return view;
    }

    View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.ll_arrow_down:
                    popupWindow.showAsDropDown(top_bar);
                    break;
                case R.id.ll_arrow_up:
                    popupWindow.dismiss();
                    break;
                case R.id.ll_search:
                    getActivity().startActivity(new Intent(getActivity(), SearchActivity.class));
                    break;
                case R.id.rl_message:
                    getActivity().startActivity(new Intent(getActivity(), MessageActivity.class));
                    break;
            }
        }
    };

    private void initFragment() {
        List<HeaderViewPagerFragment> fragments = new ArrayList<HeaderViewPagerFragment>();
        TopicFragment2 topicFragment = new TopicFragment2();
        topicFragment.setValue(tagBeanList.get(0));

//        Bundle bundle = new Bundle();
//        bundle.putSerializable("tag", tagBeanList.get(0));
//        topicFragment.setArguments(bundle);

        fragments.add(topicFragment);
        for (int i = 1; i < tagBeanList.size(); i++) {
            NewsFragment newsFragment = new NewsFragment();
            newsFragment.setValue(tagBeanList.get(i));

//            Bundle bundle1 = new Bundle();
//            bundle.putSerializable("tag", tagBeanList.get(i));
//            topicFragment.setArguments(bundle1);

            fragments.add(newsFragment);
        }
        final MainTabFragmentAdapter tabFragmentAdapter = new MainTabFragmentAdapter(fragments, tagBeanList, getChildFragmentManager(), getActivity());
        vp.setAdapter(tabFragmentAdapter);
        tl.setupWithViewPager(vp);
        for (int i = 0; i < tl.getTabCount(); i++) {
            TabLayout.Tab tab = tl.getTabAt(i);
            tab.setCustomView(tabFragmentAdapter.getTabView(i));
        }

        vp.setCurrentItem(0, false);
        TabLayout.Tab tab = tl.getTabAt(0);
        View view = tab.getCustomView();
        TextView tv_tab = (TextView) view.findViewById(R.id.tv_tab);
        ImageView iv_tab_point = (ImageView) view.findViewById(R.id.iv_tab_point);
        iv_tab_point.setVisibility(View.GONE);
        tv_tab.setTextColor(getResources().getColor(R.color.colorPrimary));

        tl.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
//                vp.setCurrentItem(tab.getPosition(), false);
                View view = tab.getCustomView();
                TextView tv_tab = (TextView) view.findViewById(R.id.tv_tab);
                ImageView iv_tab_point = (ImageView) view.findViewById(R.id.iv_tab_point);
                iv_tab_point.setVisibility(View.GONE);
                tv_tab.setTextColor(getResources().getColor(R.color.colorPrimary));
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                View view = tab.getCustomView();
                TextView tv_tab = (TextView) view.findViewById(R.id.tv_tab);
                tv_tab.setTextColor(getResources().getColor(R.color.color212121));
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    private void initPopupWindow() {
        layout = LayoutInflater.from(getActivity()).inflate(
                R.layout.layout_main_popupwindow, null);
        popupWindow = new PopupWindow(layout, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        GridView gridView = (GridView) layout.findViewById(R.id.gv_tab);
        ll_arrow_up = (LinearLayout) layout.findViewById(R.id.ll_arrow_up);
        ll_arrow_up.setOnClickListener(onClickListener);
        TabAdapter tabAdapter = new TabAdapter();
        gridView.setAdapter(tabAdapter);
    }

    private class TabAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return tagBeanList.size();
        }

        @Override
        public Object getItem(int i) {
            return tagBeanList.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(final int i, View view, ViewGroup viewGroup) {
            ViewHolder holder;
            if (view == null) {
                holder = new ViewHolder();
                view = View.inflate(getActivity(), R.layout.item_topic_tab, null);
                holder.btn = (Button) view.findViewById(R.id.btn);
                view.setTag(holder);
            } else {
                holder = (ViewHolder) view.getTag();
            }
            holder.btn.setText(tagBeanList.get(i).getTitle());
            holder.btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    vp.setCurrentItem(i);
                    popupWindow.dismiss();
                }
            });
            return view;
        }
    }

    class ViewHolder {
        Button btn;
    }

    private void initTag() {
        OkGoRequest.get(UrlUtils.GETCATE, getActivity(), "getcate", CacheMode.REQUEST_FAILED_READ_CACHE, new StringCallback() {
            @Override
            public void onCacheSuccess(String s, Call call) {
                super.onCacheSuccess(s, call);
                onSuccess(s, call, null);
            }

            @Override
            public void onSuccess(String s, Call call, Response response) {
                try {
                    JSONObject result = new JSONObject(s);
                    tagBeanList = JSON.parseArray(result.getJSONArray("data").toString(), TagBean.class);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                initFragment();
            }
        });
    }

    private void getMessageCount() {
        HttpParams httpParams = new HttpParams();
        httpParams.put("uid", BaseApp.getModel().getId());
        OkGoRequest.post(UrlUtils.WEIDU, getActivity(), "weidu", CacheMode.REQUEST_FAILED_READ_CACHE, httpParams, new StringCallback() {
            @Override
            public void onCacheSuccess(String s, Call call) {
                super.onCacheSuccess(s, call);
                onSuccess(s, call, null);
            }
            
            @Override
            public void onSuccess(String s, Call call, Response response) {
                try {
                    JSONObject result = new JSONObject(s);
                    String num = result.getString("data");
                    if (TextUtils.isEmpty(num) || "0".equals(num)) {
                        tv_message_num.setVisibility(View.GONE);
                        tv_message_num.setText("0");
                    } else {
                        tv_message_num.setVisibility(View.VISIBLE);
                        tv_message_num.setText(num);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
